<template>
  <q-page :class="songHistory.length === 0 || !isClicked ? 'flex flex-center' : ''">
    <div v-if="songHistory.length === 0 || !isClicked" style="height: 100%">
      <img
        alt="音乐播放器"
        src="home.png"
        style="width: 200px; height: 200px; cursor: pointer"
        @click="handleClickIcon"
      />
      <div
        class="row text-center text-caption text-blue"
        v-if="songHistory.length === 0"
        style="justify-content: center; cursor: pointer"
        @click="handleImport"
      >
        点击我导入本地播放记录
      </div>
      <div
        class="row text-center text-caption text-blue"
        v-if="!isClicked && songHistory.length != 0"
        style="justify-content: center; cursor: pointer"
      >
        点击查看播放记录
      </div>
      <div
        class="row text-center text-caption text-blue"
        v-if="(!isClicked && !isLogin) || (!isLogin && songHistory.length === 0)"
        style="justify-content: center; cursor: pointer"
        @click="handleLogin"
      >
        登录
      </div>
      <div
        class="row text-center text-caption text-blue"
        v-if="isLogin && songHistory.length === 0"
        style="justify-content: center; cursor: pointer"
        @click="handleScan"
      >
        扫描网盘导入音乐
      </div>
    </div>
    <div v-if="songHistory.length != 0 && isClicked" class="full-width list-style">
      <div class="text-h6 q-pa-md row">
        <div class="col">播放记录</div>
        <q-space></q-space>
        <q-btn dense flat color="primary" icon="wifi" @click="handleScan" v-if="isLogin"> </q-btn>
        <q-btn dense flat color="primary" icon="https" @click="handleLogin" v-else> </q-btn>
        <q-btn dense flat color="primary" icon="save_alt" @click="handleImport"> </q-btn>
        <q-btn dense flat icon="ios_share" color="primary" @click="handleExport"> </q-btn>
        <q-btn dense flat icon="delete" color="primary" @click="clearHistory"> </q-btn>
      </div>
      <q-list bordered separator>
        <q-item
          v-for="(song, index) in songHistory"
          :key="index"
          :class="{ 'bg-grey-3': song.url === currentSong.url }"
        >
          <q-item-section avatar>
            <q-icon name="music_note" color="primary" />
          </q-item-section>
          <q-item-section>
            <q-item-label>{{ song.title }}</q-item-label>
            <q-item-label caption>{{ song.artist }}</q-item-label>
          </q-item-section>
          <q-item-section side>
            <q-item-label caption>
              {{ formatTime(song.duration) }}
            </q-item-label>
          </q-item-section>
          <q-item-section side>
            <q-btn
              flat
              round
              dense
              icon="skip_next"
              @click.stop="$emit('play-song', index)"
              v-if="song.url != currentSong.url"
            />
          </q-item-section>
        </q-item>
      </q-list>
    </div>
    <q-inner-loading :showing="isLoading">
      <q-spinner-ios style="top: 30px; left: 20px" color="primary" size="20px" />
    </q-inner-loading>
  </q-page>
</template>

<script setup>
import { api } from 'boot/axios'
import { ref } from 'vue'
import { useQuasar } from 'quasar'

const $q = useQuasar()
const props = defineProps({
  currentSong: {
    type: Object,
    required: true,
  },
  songHistory: {
    type: Array,
    default: () => [],
  },
  isClicked: {
    type: Boolean,
    default: false,
  },
  isLogin: {
    type: Boolean,
    default: false,
  },
})
const emit = defineEmits(['update-duration', 'clear-history', 'play-song', 'refresh-history'])

const handleClickIcon = () => {
  if (props.songHistory.length === 0) {
    handleImport()
  }
}
const isLoading = ref(false)
const handleScan = async () => {
  try {
    isLoading.value = true
    await api.post('/api/v1/music_json_service', null, {
      headers: {
        ApiKey: btoa(
          `${localStorage.getItem('token') || ''}` +
            '$$' +
            `${localStorage.getItem('email') || ''}`,
        ),
      },
    })
    emit('refresh-history')
  } catch (ex) {
    console.log(ex)
    // if response has exists "message or error". use $q.Notify to show the message/error in top
    if (ex.response?.data?.message) {
      $q.notify({
        message: '扫描网盘失败：' + ex.response.data.message,
        color: 'negative',
        position: 'top',
      })
    }
    if (ex.response?.data?.error) {
      $q.notify({
        message: '扫描网盘失败：' + ex.response.data.error,
        color: 'negative',
        position: 'top',
      })
    }
  } finally {
    isLoading.value = false
  }
}

const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
}

const clearHistory = () => {
  $q.dialog({
    title: '确认',
    message: '确定要清空所有播放记录吗？',
    cancel: true,
    persistent: true,
  }).onOk(() => {
    emit('clear-history')
  })
}

const handleLogin = () => {
  const encode = encodeURIComponent
  window.location.href = `https://login.zhuchundashuaige.com/#/?RedirectUri=${encode(
    'http://' + window.location.host,
  )}&Type=SPA`
}

const handleImport = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  input.onchange = (e) => {
    const file = e.target.files[0]
    const reader = new FileReader()
    reader.onload = (event) => {
      try {
        const data = JSON.parse(event.target.result)
        emit('import-history', data)
      } catch (error) {
        console.error('导入失败:', error)
      }
    }
    reader.readAsText(file)
  }
  input.click()
}

const handleExport = () => {
  const dataStr = JSON.stringify(props.songHistory)
  const dataUri = 'data:application/json;charset=utf-8,' + encodeURIComponent(dataStr)

  const exportFileDefaultName = '播放历史.json'

  const linkElement = document.createElement('a')
  linkElement.setAttribute('href', dataUri)
  linkElement.setAttribute('download', exportFileDefaultName)
  linkElement.click()
}
</script>

<style scoped>
.list-style {
  width: 100%;
  max-width: 1000px;
  justify-self: center;
}
</style>
